package Client;

import Util.Constant;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * @Author:AwakeningCode
 * @Date: Created in 8:58 2018\1\19 0019
 */
public class NettyClient extends Thread{

    public static String host = "127.0.01";
    ClientBootstrap bootstrap;
    int port;

    //创建1个线程池
    static ExecutionHandler executionHandler = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16,1048576,1048576));

    public NettyClient(int port){
        this.port = port;
        //ChannelFactory
        final ChannelFactory channelFactory = new NioClientSocketChannelFactory(
                //Boss线程池
                Executors.newCachedThreadPool(),
                //Worker线程池
                Executors.newCachedThreadPool()
        );
        //ServerBootstrap
        bootstrap = new ClientBootstrap(channelFactory);

        ClientPipelineFactory clientPipelineFactory = new ClientPipelineFactory(executionHandler);
        bootstrap.setPipelineFactory(clientPipelineFactory);
        bootstrap.setOption("tcpNoDelay" ,true);
        bootstrap.setOption("keepAlive", true);
        bootstrap.connect(new InetSocketAddress(port));
    }

    public void run(){
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,port));
        //开始试图连接
        System.out.println("Connecting to port " + port + "...");
        //等待直到连接关闭或失败
        future.getChannel().getCloseFuture().awaitUninterruptibly();
        //关闭线程池准备退出
        bootstrap.releaseExternalResources();
    }

    public static void main(String[] args) {
        NettyClient nc1 = new NettyClient(Constant.p1);
        NettyClient nc2 = new NettyClient(Constant.p2);
        NettyClient nc3 = new NettyClient(Constant.p3);
        NettyClient nc4 = new NettyClient(Constant.p4);
        NettyClient nc5 = new NettyClient(Constant.p5);

        nc1.start();
        nc2.start();
        nc3.start();
        nc4.start();
        nc5.start();
    }

}
